package 笔试.面试手撕;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author:谢君臣
 * @Date:2021/9/9-9:43
 * @version:1.0
 * @function:
 */
public class 可重入锁 {
    public static void main(String[] args) {
        MyLock lock = new MyLock();
        new Thread(()->{
            lock.lock();
            try {
                lock.lock();
                System.out.println("加锁成功");
                try {
                    System.out.println("加锁成功");
                    TimeUnit.SECONDS.sleep(5);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                    System.out.println("解锁成功");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
                System.out.println("解锁成功");
            }
        }).start();

    }
}

class MyLock implements Lock {

    class MySyn extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            int s = getState();
            if (s == 0 && compareAndSetState(0, 1)) {
                // 加锁成功
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            if (getExclusiveOwnerThread() == Thread.currentThread()) // 重复获取锁
            {
                setState(arg + s);
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            int state = getState();
            if (compareAndSetState(state, state - 1)) {
                if (state == 1)
                    setExclusiveOwnerThread(null);
                return true;
            }
            return false;
        }

        @Override
        protected boolean isHeldExclusively() {
            return super.isHeldExclusively();
        }

        public Condition getCondition() {
            return new ConditionObject();
        }
    }

    private MySyn syn = new MySyn();

    @Override
    public void lock() {
        syn.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        syn.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return syn.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return syn.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        syn.release(1);
    }

    @Override
    public Condition newCondition() {
        return syn.getCondition();
    }
}